package synch;

import java.util.concurrent.locks.*;

/**
 * A bank with a number of bank accounts that uses locks for serializing access.
 * @author andy
 */
public class Bank {

    private final double[] accounts;
    private Lock bankLock;
    private Condition sufficientFunds;

    public Bank(int n, double initialBalance) {
        this.accounts = new double[n];
        for (int i = 0; i < this.accounts.length; i++) {
            this.accounts[i] = initialBalance;
        }
        this.bankLock = new ReentrantLock();
        this.sufficientFunds = this.bankLock.newCondition();
    }

    public void transfer(int from, int to, double amount) throws InterruptedException {
        this.bankLock.lock();
        try {
            while(this.accounts[from] < amount) {
                this.sufficientFunds.await();
            }
            System.out.print(Thread.currentThread());
            this.accounts[from] -= amount;
            System.out.printf(" %10.2f from %d to %d", amount, from, to);
            this.accounts[to] += amount;
            System.out.printf(" Total Balance: %10.2f\n", getTotalBalance());
            this.sufficientFunds.signalAll();
        } finally {
            this.bankLock.unlock();
        }
    }

    public double getTotalBalance() {
        this.bankLock.lock();
        try {
            double sum = 0;
            for (double a : accounts) {
                sum += a;
            }
            return sum;
        } finally {
            this.bankLock.unlock();
        }
    }

    public int size() {
        return this.accounts.length;
    }
}
